#!/bin/bash

# iOS 模拟器启动脚本
# 用于快速启动 iOS 模拟器进行 UniApp 应用测试

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Xcode 是否安装
check_xcode() {
    if ! command -v xcrun &> /dev/null; then
        print_error "未找到 Xcode 命令行工具"
        print_info "请先安装 Xcode，然后运行："
        echo "  xcode-select --install"
        exit 1
    fi
}

# 检查模拟器是否已经在运行
check_simulator_running() {
    booted_devices=$(xcrun simctl list devices | grep "Booted" | wc -l)
    if [ $booted_devices -gt 0 ]; then
        return 0
    else
        return 1
    fi
}

# 列出所有可用的 iOS 模拟器
list_simulators() {
    print_info "可用的 iOS 模拟器设备："
    echo ""
    xcrun simctl list devices available | grep -E "iPhone|iPad" | grep -v "unavailable"
}

# 获取模拟器设备列表
get_simulator_list() {
    xcrun simctl list devices available | grep -E "iPhone|iPad" | grep "Shutdown\|Booted" | sed 's/^[[:space:]]*//'
}

# 启动模拟器
start_simulator() {
    local device_udid=$1
    local device_name=$2
    
    print_info "正在启动模拟器: $device_name"
    print_info "设备 ID: $device_udid"
    
    # 启动模拟器
    xcrun simctl boot "$device_udid" 2>/dev/null
    
    if [ $? -eq 0 ]; then
        print_success "模拟器启动成功"
    else
        # 可能已经在运行
        if xcrun simctl list devices | grep "$device_udid" | grep "Booted" > /dev/null; then
            print_warning "模拟器已在运行"
        else
            print_error "模拟器启动失败"
            return 1
        fi
    fi
    
    # 打开模拟器应用窗口
    print_info "打开模拟器应用窗口..."
    open -a Simulator
    
    sleep 2
    return 0
}

# 显示模拟器信息
show_simulator_info() {
    print_info "当前运行的模拟器："
    echo ""
    xcrun simctl list devices | grep "Booted"
    echo ""
    
    # 获取第一个运行中的模拟器信息
    local booted_udid=$(xcrun simctl list devices | grep "Booted" | head -1 | grep -oE '[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}')
    
    if [ -n "$booted_udid" ]; then
        print_info "模拟器详细信息："
        
        # 获取设备信息
        local device_info=$(xcrun simctl list devices | grep "$booted_udid")
        local device_name=$(echo "$device_info" | sed 's/\(.*\) (.*/\1/' | xargs)
        
        echo "- 设备名称: $device_name"
        echo "- 设备 UDID: $booted_udid"
        echo "- iOS 版本: $(xcrun simctl list devices | grep -B10 "$booted_udid" | grep "^--" | tail -1 | sed 's/-- //')"
        
        # 获取设备类型
        local device_type=$(xcrun simctl list devices | grep "$booted_udid" | grep -oE "iPhone|iPad" || echo "Unknown")
        echo "- 设备类型: $device_type"
    fi
}

# 主函数
main() {
    echo "=================================="
    echo "  iOS 模拟器启动脚本"
    echo "=================================="
    echo ""
    
    # 检查 Xcode
    check_xcode
    
    # 检查是否已有模拟器在运行
    if check_simulator_running; then
        print_warning "检测到模拟器已在运行"
        show_simulator_info
        echo ""
        read -p "是否要启动新的模拟器？(y/N): " answer
        if [[ ! $answer =~ ^[Yy]$ ]]; then
            print_info "使用现有模拟器"
            open -a Simulator
            exit 0
        fi
    fi
    
    # 列出可用的模拟器
    list_simulators
    echo ""
    
    # 获取模拟器列表
    local simulators=()
    local simulator_udids=()
    
    while IFS= read -r line; do
        if [ -n "$line" ]; then
            simulators+=("$line")
            # 提取 UDID (匹配标准 UUID 格式)
            udid=$(echo "$line" | grep -oE '[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}')
            simulator_udids+=("$udid")
        fi
    done < <(get_simulator_list)
    
    if [ ${#simulators[@]} -eq 0 ]; then
        print_error "未找到可用的 iOS 模拟器"
        print_info "请在 Xcode 中创建模拟器："
        echo "  Xcode -> Window -> Devices and Simulators -> Simulators"
        exit 1
    fi
    
    # 默认选择 iPhone（优先选择 iPhone 17 Pro）
    local default_index=0
    for i in "${!simulators[@]}"; do
        if echo "${simulators[$i]}" | grep -q "iPhone 17 Pro"; then
            default_index=$i
            break
        elif echo "${simulators[$i]}" | grep -q "iPhone 17"; then
            default_index=$i
        fi
    done
    
    # 如果只有一个模拟器，直接使用它
    if [ ${#simulators[@]} -eq 1 ]; then
        selected_index=0
    else
        # 让用户选择模拟器
        print_info "请选择要启动的模拟器（直接回车使用默认设备）:"
        echo ""
        for i in "${!simulators[@]}"; do
            if [ $i -eq $default_index ]; then
                echo "  $((i+1))) ${simulators[$i]} [默认]"
            else
                echo "  $((i+1))) ${simulators[$i]}"
            fi
        done
        echo ""
        read -p "请输入编号 [默认: $((default_index+1))]: " choice
        
        if [ -z "$choice" ]; then
            selected_index=$default_index
        else
            selected_index=$((choice-1))
            if [ $selected_index -lt 0 ] || [ $selected_index -ge ${#simulators[@]} ]; then
                print_error "无效的选择"
                exit 1
            fi
        fi
    fi
    
    # 启动选定的模拟器
    local device_udid="${simulator_udids[$selected_index]}"
    local device_name=$(echo "${simulators[$selected_index]}" | sed 's/\(.*\) (.*/\1/' | xargs)
    
    if start_simulator "$device_udid" "$device_name"; then
        echo ""
        show_simulator_info
        echo ""
        print_success "模拟器已就绪，可以开始开发了！"
        echo ""
        print_info "提示："
        echo "- 安装应用: xcrun simctl install <device_udid> <app_path>"
        echo "- 启动应用: xcrun simctl launch <device_udid> <bundle_id>"
        echo "- 查看设备: xcrun simctl list devices"
        echo "- 关闭模拟器: xcrun simctl shutdown <device_udid>"
        echo "- 关闭所有: xcrun simctl shutdown all"
    else
        print_error "模拟器启动失败"
        exit 1
    fi
}

# 运行主函数
main

